package cc.mrbird.web.service.impl;

import cc.mrbird.common.service.impl.BaseService;
import cc.mrbird.system.domain.MidStudent;
import cc.mrbird.web.dao.MidStudentMapper;
import cc.mrbird.web.dao.StudentMapper;
import cc.mrbird.system.domain.Student;
import cc.mrbird.web.domain.RespImport;
import cc.mrbird.web.hanlder.MidStudentExcelHandler;
import cc.mrbird.web.hanlder.StudentExcelHandler;
import cc.mrbird.web.service.StudentService;
import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import cn.afterturn.easypoi.handler.inter.IExcelDataHandler;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;


@Service("studentService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class StudentServiceImpl extends BaseService<Student> implements StudentService{

    private static final Logger log = LoggerFactory.getLogger(StudentServiceImpl.class);

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private MidStudentMapper midStudentMapper;

    @Override
    public void addStudent(Student student,String userName) {
        student.setCreatedTime(new Date());
        student.setUpdatedTime(new Date());
        student.setUserName(userName);
        this.save(student);
        log.info("插入学生信息成功");
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void updateStudent(Student student) {

        student.setUpdatedTime(new Date());
        studentMapper.updateStudent(student);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, readOnly = false)
    public void deleteStudents(String studentIds) {

        List<String> list = Arrays.asList(studentIds.split(","));
        this.batchDelete(list, "id", Student.class);
    }

    @Override
    @Transactional
    public RespImport ImportStudent(MultipartFile file,String userName) {
        ImportParams importParams = new ImportParams();
        // 数据处理
        IExcelDataHandler<Student> handler = new StudentExcelHandler();
        handler.setNeedHandlerFields(new String[] { "考生号" });// 注意这里对应的是excel的列名。也就是对象上指定的列名。
        importParams.setDataHanlder(handler);

        // 需要验证
        importParams.setNeedVerfiy(true);

        List<Student> successList = null;
        List<Student> failList = null;
        int successNum = 0,failureNum =0,repeatNum = 0;
        RespImport respImport = new RespImport();
        String tempRepeatStudentId = null;
        String tempFailureStudentId = null;
        try {
            ExcelImportResult<Student> result = ExcelImportUtil.importExcelMore(file.getInputStream(), Student.class,
                    importParams);

            successList = result.getList();
            failList = result.getFailList();

            log.info("是否存在验证未通过的数据:" + result.isVerfiyFail());
            log.info("验证通过的数量:" + successList.size());
            log.info("验证未通过的数量:" + failList.size());

        } catch (IOException e) {
            log.error(e.getMessage(), e);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

        for ( Student student : successList) {
            student.setUserName(userName);
            student.setCreatedTime(new Date());
            student.setUpdatedTime(new Date());
            Student result = this.studentMapper.findById(student.getStudentId());
            if (result != null){
                repeatNum++;
                failureNum++;
                tempRepeatStudentId += result.getStudentId()+"、";
                tempRepeatStudentId = tempRepeatStudentId.replace("null","");
                respImport.setRepeatStudentId(tempRepeatStudentId);
                log.info("考生号已存在:" + result.getStudentId() );
            }
            if (result == null)
            studentMapper.insert(student);
            //log.info("成功列表信息:ID=" + student.getStudentId() + student.getName() );
            successNum++;
        }
        for (Student student : failList) {
            /*student.setStatus("可疑");
            student.setUserName(userName);
            student.setCreatedTime(new Date());
            student.setUpdatedTime(new Date());
            Student result = this.studentMapper.findById(student.getStudentId());
            if (result != null)
            log.info("考生号已存在:" + result.getStudentId() );
            if (result == null)
            studentMapper.insert(student);*/
            tempFailureStudentId += student.getStudentId()+"、";
            tempFailureStudentId = tempFailureStudentId.replace("null","");
            respImport.setFailureStudentId(tempFailureStudentId);
            //log.info("失败列表信息:" + student.getStudentId() + student.getName() );
            failureNum++;
        }
        respImport.setSuccessNum(successNum-repeatNum);
        respImport.setFailureNum(failureNum);
        return respImport;
    }

    @Override
    public List<Student> findStudentAll() {
        return studentMapper.findStudentAll();
    }

    @Override
    public List<Student> findStudentByCondition(Student student) {
        return studentMapper.findStudentByCondition(student);
    }

    /**
     * 根据id查找考生信息
     * @param studentId
     * @return
     */
    @Override
    public Student findById(String studentId) {
        return studentMapper.findById(studentId);
    }

}
